<!--
 * @Author: xiaotiwen
 * @Date: 2020-05-08 18:14:48
 * @LastEditTime: 2020-07-22 16:25:15
 * @LastEditors: xiaotiwen
 * @FilePath: \eduweb\src\views\practiceManagement\dispersionPracticeApply\index.vue
 * @Description: 分散实习申请
 -->
<template>
    <div class="disPraApply">
        <inner-breadcrumb v-model="pathKey" :path="path" />
        <div v-if="pathKey==='main'">
            <ConditionCard shadow="never" label-width="120px" @search="onSubmit" @reset="reset('queryForm')">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('label.schoolTerm')">
                                <CalendarSelect v-model="queryForm.yearTerm" @load-done="loadDone" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.grade')">
                                <el-date-picker v-model="queryForm.grade" value-format="yyyy" type="year" :placeholder="$t('message.plzSelect')" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('fundingManagement.label.courseOpenAcademy')">
                                <DictSelect v-model="queryForm.courseOpenAcademyId" :data="options.courseOpenAcademyId" :clearable="false" :filterable="true"></DictSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('courseConfirmation.label.stuFaculty')">
                                <DictSelect v-model="queryForm.acdemyId" :data="options.acdemyId" :clearable="false" :filterable="true" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.major')">
                                <MyMajor :faculty="queryForm.acdemyId" :grade="queryForm.grade" v-model="queryForm.majorId" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('courseSummary.aduitType')">
                                <el-select v-model="queryForm.status" style="width: 100%" clearable>
                                    <el-option v-for="(item, idx) in options.status" :key="idx" :value="item.value" :label="item.label" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
            </ConditionCard>
            <el-card shadow="never" body-style="padding: 24px;">
                <h2 class="disPraApply_titles">{{$t('dispersionPracticeApply.title.listTitle')}}</h2>
                <div class="edu-opertion-bar">
                    <div class="float-left">
                        <KeywordInput v-if="!global.isStudent" v-model="queryForm.studentNameNum" :placeholder="$t('dispersionPracticeApply.tips.plzInputNameOrCode')" @enter="onSubmit"></KeywordInput>
                        <!-- <el-input v-if="!global.isStudent" v-model="queryForm.studentNameNum" maxlength="30" style="width: 200px;" :placeholder="$t('dispersionPracticeApply.tips.plzInputNameOrCode')" prefix-icon="el-icon-search" @change="onSubmit" /> -->
                    </div>
                    <div class="float-right">
                        <el-button type="primary" v-if="authsBtnState.exportState" @click="handleExportSchemes">{{ $t('message.export') }}</el-button>
                        <el-button type="primary" v-if="authsBtnState.batchReviewState" @click="audits">{{ $t('dispersionPracticeApply.btn.batchCheck') }}</el-button>
                        <el-button type="primary" v-if="authsBtnState.addState" @click="add('')">{{ $t('message.add') }}</el-button>
                    </div>
                </div>
            </el-card>
            <edu-table ref="tables" :data="data" :order="true" :orderFixed="true" :total="total" :page-size="page.pageSize_" @page-change="handleSizeChange" :selectFixed="true">
                <el-table-column v-for="(item) in label" :min-width="item.width" :key="item.props" :label="item.label" :prop="item.props" :sortable="item.sortable" align="center" :fixed="item.fixed" />
                <el-table-column min-width="100" align="center" :label="$t('courseSummary.aduitType')" prop="status" fixed="right" >
                    <template slot-scope="scope">
                        <el-tag v-for="item in options.status" :key="item.value" v-if="item.value===scope.row.status" :type="item.types" class="tagClass" effect="plain"> {{ item.label }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="130px" :label="$t('message.operating')" fixed="right">
                    <template slot-scope="scope">
                        <div class="disPraApply_btns" @click.stop="">
                            <el-button v-if="global.isAcdemicDean && authsBtnState.auditButState&&scope.row.status === 'ACADEMY_INPROCESS'" type="text" @click="open('auditFculty', scope.row.id)">{{$t('message.check')}}</el-button>
                            <el-button v-if="global.isAnyTeacher && authsBtnState.auditButState&&scope.row.status === 'INSTRUCTOR_INPROCESS'" type="text" @click="open('auditTeacher', scope.row.id)">{{$t('message.check')}}</el-button>
                            <el-button v-if="(scope.row.status === 'DRAFT'||scope.row.status === 'REJECTED')&&authsBtnState.editState" type="text" @click="add(scope.row.id)">{{$t('message.edit')}}</el-button>
                            <el-button v-if="scope.row.status === 'DRAFT'&&authsBtnState.deleteState" type="text" @click="del(scope.row.id)">{{$t('message.delete')}}</el-button>
                            <el-button v-if="authsBtnState.detailsState" type="text" @click="open('details', scope.row.id)">{{$t('message.detail')}}</el-button>
                        </div>
                    </template>
                </el-table-column>
            </edu-table>
        </div>
        <!-- 批量审核弹框 -->
        <el-dialog :title="$t('dispersionPracticeApply.btn.batchCheck')" width="400px" :visible.sync="dialogFlag1" v-if="dialogFlag1" :close-on-click-modal="false">
            <el-form ref="form" :model="form" label-width="100px" :rules="rules">
                <el-form-item :label="$t('practiceManagement.opinion')">
                    <el-input type="textarea" rows="4" v-model.trim="form.auditRemark" maxlength="200" resize="none"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFlag1=false">{{$t('message.cancel')}}</el-button>
                <el-button type="danger" @click="audit('reject')">{{$t('message.reject')}}</el-button>
                <el-button type="primary" @click="audit('pass')">{{$t('message.pass')}}</el-button>
            </div>
        </el-dialog>
        <!-- 指导老师审核/ 学院审核/ 详情-->
        <dispersionPracticeAudit v-if="pathKey==='auditTeacher'||pathKey==='auditFculty'||pathKey==='details'" :type="types" ref="audits" :ids="ids" @cancle-emit="cancels" :dataInfo="dataInfo" :fromCheckDetail="fromCheckDetail" :pathKey="pathKey"/>
        <!-- 详情 -->
        <!-- <dispersionPracticeDetails v-if="pathKey === 'details'" ref="details" :ids="ids" @cancel="cancels" /> -->
        <!-- 分散实习申请、编辑 -->
        <el-dialog :visible="dialogFlag" :close-on-click-modal="false" :title="$t('dispersionPracticeApply.title.dialogTitle')" width="926px" @close="dialogFlag = false" >
            <practiceApply ref="apply" v-if="dialogFlag"
                :ids="ids"
                :yearTerm="yearTerms"
                :chooseFlag="chooseFlag"
                :showStuFlag="showStuFlag"
            />
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFlag= false">{{$t('message.cancel')}}</el-button>
                <el-button v-if="(!global.isAdmin&&!global.isAcdemicDean)" type="primary" @click="dataSend('save')">{{$t('message.save')}}</el-button>
                <el-button type="primary" @click="dataSend('submit')">{{$t('message.submit')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { findDept } from 'common/src/api/user'
import commonMixins from '../commonMixins';
import dispersionPracticeAudit from './dispersionPracticeAudit';
import practiceApply from './practiceApply';
import dispersionPracticeDetails from './dispersionPracticeDetails';
import { getList, deleteById, dataSubmit, addSave, exportData } from 'common/src/api/practiceManagement/dispersionPracticeApply';
import { throughBatch, rejectBatch } from 'common/src/api/studentRegister';
import { mapState } from 'vuex';
import MyMajor from "common/src/views/practiceManagement/common/MyMajor";
import mixin from 'common/src/mixins/index';
export default {
    // 组件名称
    name: 'DispersionPracticeApply',
    // 局部注册的组件
    components: {
        dispersionPracticeAudit,
        practiceApply,
        dispersionPracticeDetails,
        MyMajor
    },
    mixins: [commonMixins,mixin],
    // 组件参数 接收来自父组件的数据
    props: {
      dataInfo: {
        type: Object,
        default: {}
      },
      fromCheckDetail:{
        type: Boolean,
        required: false
      },
    },
    // 组件状态值
    data() {
        return {
            dialogFlag: false,
            dialogFlag1: false,
            yearTerms: '',
            ids: '',
            form: {
                auditRemark: ''
            },
            page: {
                pageNum_: 1,
                pageSize_: 20
            },
            total: 0,
            queryForm: {
                yearTerm: '', // 学期学年
                courseOpenAcademyId:'',//开课学院
                acdemyId: '', // 学院
                grade: '', // 年级
                majorId: '', // 专业
                status: '', // 状态
                studentNameNum: '' // 学生学号或者姓名
            },
            options: {
                acdemyId: [], // 学院
                courseOpenAcademyId:[],//开课学院
                grade: [], // 年级
                majorId: [], // 专业
                status: [
                    { label: this.$t('practiceManagement.status.draft'), value: 'DRAFT', types: 'info' },
                    { label: this.$t('practiceManagement.status.inFaculty'), value: 'ACADEMY_INPROCESS', types: 'info' },
                    { label: this.$t('practiceManagement.status.inTutor'), value: 'INSTRUCTOR_INPROCESS', types: 'info' },
                    { label: this.$t('practiceManagement.status.approved'), value: 'APPROVED', types: 'success' },
                    { label: this.$t('practiceManagement.status.rejected'), value: 'REJECTED', types: 'warning' }
                ] // 状态
            },
            data: [],
            label: [
                { label: this.$t('fundingManagement.label.courseProgramNumber'), props: 'subCourseNo', width: 100, sortable: true},
                { label: this.$t('fundingManagement.label.courseName'), props: 'courseName', width: 100, sortable: true},
                { label: this.$t('label.stuCode'), props: 'studentNo', width: 90, sortable: true, fixed: 'left' },
                { label: this.$t('label.stuName'), props: 'studentName', width: 90, sortable: true, fixed: 'left' },
                { label: this.$t('fundingManagement.label.courseOpenAcademy'), props: 'courseOpenAcademy', width: 180 },
                { label: this.$t('courseConfirmation.label.stuFaculty'), props: 'acdemyName', width: 180, sortable: true },
                { label: this.$t('label.grade'), props: 'grade', width: 100, sortable: true },
                { label: this.$t('label.major'), props: 'majorName', width: 180, sortable: true },
                { label: this.$t('dispersionPracticeApply.label.practiceDate'), props: 'practiceDate', width: 200, sortable: true },
                { label: this.$t('dispersionPracticeApply.label.practiceAddr'), props: 'practiceAddr', width: 100, sortable: true },
                { label: this.$t('dispersionPracticeApply.label.practiceEnterprise'), props: 'practiceEnterprise', width: 130, sortable: true },
                { label: this.$t('dispersionPracticeApply.label.enterpriseContactUser'), props: 'enterpriseContactUser', width: 130, sortable: true },
                { label: this.$t('dispersionPracticeApply.label.position'), props: 'position', width: 130, sortable: true },
                { label: this.$t('dispersionPracticeApply.label.enterpriseContactPhone'), props: 'enterpriseContactPhone', width: 120, sortable: true }
            ],
            pathKey: this.$route.query.pathKey?this.$route.query.pathKey:'main',
            path: {
                label: this.$t('dispersionPracticeApply.title.dialogTitle'),
                key: 'main',
                disable: false,
                children: [
                    { label: this.$t('message.edit'), key: 'apply', disable: true },
                    { label: this.$t('message.detail'), key: 'details', disable: true },
                    { label: this.$t('dispersionPracticeApply.path.auditTeacher'), key: 'auditTeacher', disable: true },
                    { label: this.$t('dispersionPracticeApply.path.auditFculty'), key: 'auditFculty', disable: true }
                ]
            },
            auths: [],
            authsBtnState: {
              addState: false, // 新增
              editState: false, // 编辑
              deleteState: false,   // 删除
              exportState: false,   // 导出
              detailsState: false, // 详情
              auditButState: false, // 审核
              batchReviewState: false, // 批量审核
            },
            chooseFlag:false,
            showStuFlag:false
        };
    },
    // 计算属性
    computed: {
        ...mapState['getGlobal']
    },
    // 侦听器
    watch: {
      auths: {
        handler(newVal) {
          if (newVal && Array.isArray(newVal) && newVal.length > 0) {
            newVal.some(item => {
              // 新增
              if (item.authCode === 'dispersionPracticeApply-add') {
                this.authsBtnState.addState = true;
              }
              // 编辑
              if (item.authCode === 'dispersionPracticeApply-edit') {
                this.authsBtnState.editState = true;
              }
              // 删除
              if (item.authCode === 'dispersionPracticeApply-delete') {
                this.authsBtnState.deleteState = true;
              }
              // 导出
              if (item.authCode === 'dispersionPracticeApply-export') {
                this.authsBtnState.exportState = true;
              }
              // 详情
              if (item.authCode === 'dispersionPracticeApply-details') {
                this.authsBtnState.detailsState = true;
              }
              // 审核
              if (item.authCode === 'dispersionPracticeApply-auditBut') {
                this.authsBtnState.auditButState = true;
              }
              // 批量审核
              if (item.authCode === 'dispersionPracticeApply-batchReview') {
                this.authsBtnState.batchReviewState = true;
              }
            });
          }
        }
      }
    },
    /**
     * 在实例初始化之后，组件属性计算之前，如data属性等
     */
    created() {
      // 获取当前用户auths权限
      if (localStorage.getItem("sessiondata")) {
        if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
          this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
        }
      }
    },
    /**
     * 在挂载开始之前被调用：相关的 render 函数首次被调用。
     */
    mounted() {
        let auths = '';
        let params = {
            X_YX: 'courseOpenAcademyId', // 学院:
            G_ZY: 'majorId' // 专业:
        };
        this.initOptions(params);
        findDept(0).then(res => {
            if (res.code == 200 && res.data) {
                this.options.acdemyId = res.data.map(row => {
                    return { label: row.deptName, value: row.deptCode }
                })
            }
        })
    },
    // 组件方法
    methods: {
        // 批量审核
        audits() {
            let selection = this.$refs.tables.selectionDatas;
            if (!selection || selection.length === 0) {
                this.$noSelectAlert();
                return;
            }
            let count = 0
            selection.forEach(t => {
                if(this.global.isAcdemicDean && t.status !== 'ACADEMY_INPROCESS'){
                    count++
                }
                if (this.global.isAnyTeacher && t.status !== 'INSTRUCTOR_INPROCESS') {
                    count++
                }
            })
            if (count > 0) {
                this.$message({
                    message: this.$t('practiceReworkManagement.tips.batchAuditTip'),
                    type: 'warning'
                })
                return
            }
            this.form.auditRemark = '';
            this.dialogFlag1 = true;
        },
        // 批量审核确定或者驳回
        audit(type) {
            let selection = this.$refs.tables.selectionDatas;
            let data = selection.map(r => {
                return {
                    no: r.workFlowId,
                    content: this.form.auditRemark
                };
            });
            if (type === 'pass') {
                throughBatch(data).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.getLists(true);
                    this.dialogFlag1 = false;
                });
            } else {
                if (!this.form.auditRemark) {
                    this.$message({ message: this.$t('dispersionPracticeApply.tips.rejectContent'), type: 'warning' });
                } else {
                    rejectBatch(data).then(res => {
                        if (res && res.code !== 200) {
                            this.$message({ message: res.msg, type: 'warning' });
                            return;
                        }
                        this.getLists(true);
                        this.dialogFlag1 = false;
                    });
                }
            }
        },
        // 删除
        del(id) {
            let jsonData = [];
            if (!id) {
                // 批量删除
                let selection = this.$refs.tables.selectionDatas;
                if (!selection || selection.length === 0) {
                    this.$noSelectAlert();
                    return;
                }
                let flag = false;
                selection.forEach(item => {
                    if (item.status !== 'DRAFT') {
                        flag = true;
                        return;
                    } else {
                        jsonData.push({ id: item.id });
                    }
                });
                if (flag) {
                    this.$message({
                        message:  this.$t('dispersionPracticeApply.tips.statusWrong'),
                        type: 'warning'
                    });
                    return;
                }
            } else {
                jsonData.push({ id: id });
            }
            this.$confirm(this.$t('message.areYouSureDelete'), this.$t('message.prompt'), {
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel'),
                type: "warning"
            }).then(() => {
                deleteById(jsonData).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.getLists(true);
                    this.$message({ type: 'success', message: this.$t('message.deleteSuccess') });
                });
            });
        },
        // 新增/编辑、保存/提交
        dataSend(val) {
            let data = this.$refs.apply.save(val);
            if (!data) {
                return;
            }
            this.$set(data, 'yearTerm', this.yearTerms);
            // 时间校验
            if (this.$refs.apply.timeChange()) {
                return;
            }
            if (val === 'save') {
                // 保存
                addSave(data).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.dialogFlag = false;
                    this.getLists(true);
                    this.$message({ message: this.$t('message.saveSuccess'), type: 'success' });
                });
            } else if (val === 'submit') {
                // 提交
                dataSubmit(data).then(res => {
                    if (res && res.code !== 200) {
                        this.$message({ message: res.msg, type: 'warning' });
                        return;
                    }
                    this.dialogFlag = false;
                    this.getLists(true);
                    this.$message({ message: this.$t('message.submitSuccess'), type: 'success' });
                });
            }
        },
        // 面包屑跳转
        open(val, ids) {
            this.ids = ids;
            this.pathKey = val;
            this.types = val;
        },
        // 打开新增、编辑
        add(val) {
            this.ids = val;
            this.dialogFlag = true;
            if(this.global.isAdmin || this.global.isAcdemicDean){
                this.showStuFlag = true;
            }else{
                this.showStuFlag = false;
            }
            this.chooseFlag = true;
            if(val){
                this.showStuFlag = false;
                this.chooseFlag = false;
            }
        },
        // 分页数量事件
        handleSizeChange(val) {
            [this.page.pageSize_, this.page.pageNum_] = [val.pageSize, val.pageNum];
            this.getLists();
        },
        // 重置
        reset() {
            for (const key in this.queryForm) {
                if (key !== 'yearTerm') {
                    this.queryForm[key] = '';
                }
            }
            this.queryForm.yearTerm = this.yearTerms;
            this.getLists(true);
        },
        // 筛选
        onSubmit() {
            this.getLists(true);
        },
        getLists(refresh) {
            if(refresh){
                this.page.pageNum_ = 1;
                if(this.$refs.tables) {
                  this.$refs.tables.pageNum = 1;
                }
            }
            let jsons = {
                condition: this.queryForm,
                pageNum_: this.page.pageNum_,
                pageSize_: this.page.pageSize_
            };
            getList(jsons).then(res => {
                this.data = res.data.list;
                this.data.forEach(item => {
                    this.$set(item, 'practiceDate', `${item.practiceDateStart ? item.practiceDateStart : ''}~${item.practiceDateEnd ? item.practiceDateEnd : ''}`);
                });
                this.total = res.data.total_;
            });
        },
        // 审核，详情返回
        cancels(val) {
            this.pathKey = 'main';
        },
        loadDone() {
            this.yearTerms = this.queryForm.yearTerm;
            this.onSubmit()
        },
        // 导出
        handleExportSchemes(type) {
            let selection = JSON.parse(JSON.stringify(this.$refs.tables.selectionDatas));
            let params = {
                exportType: 0,
                request: this.queryForm,
                responses: selection
            };
            if (selection && selection.length >= 1) {
                params.exportType = 1;
                selection.map(item => {
                    item.status = this.fieldChange(this.options.status, item.status);
                    item.practiceDateStart = new Date(item.practiceDateStart).getTime();
                    item.practiceDateEnd = new Date(item.practiceDateEnd).getTime();
                    item.updateTime = new Date(item.updateTime).getTime();
                    item.createTime = new Date(item.createTime).getTime();
                })
                exportData(params);
            } else {
                exportData(params);
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.disPraApply {
    &_btns {
        display: flex;
    }
    &_titles {
        font-weight: bold;
        color: #2b3b4e;
    }
}
.tagClass {
    width: 72px;
    overflow: hidden;
    height: auto;
    white-space: normal;
}
</style>
